import axios from 'axios'
import Vue from 'vue'
import router from '@/router'
import { Message } from 'element-ui'

const instance = axios.create({
  baseURL: 'http://localhost:8888/api/private/v1/',
  headers: {}
})

instance.interceptors.request.use(config => {
  if (config.url === 'login') return config
  config.headers.authorization = window.sessionStorage.getItem('token')
  return config
})

instance.interceptors.response.use(config => {
  if (config.data.meta.status === 401) {
    Message({
      type: 'error',
      message: '登录状态时效，请重新登录',
      duration: 3000
    })
    router.push('/login')
    return config.data
  }
  return config.data
})

const plugin = {
  install () {
    Vue.prototype.$http = instance
    Vue.prototype.$get = instance.get
    Vue.prototype.$post = instance.post
  }
}

export default plugin
